package com.cxd.blog.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cxd.blog.admin.mapper.PermissionMapper;
import com.cxd.blog.admin.model.pojo.Permission;
import com.cxd.blog.admin.service.PermissionService;
import com.cxd.blog.model.vo.Result;
import com.cxd.blog.model.vo.ResultCode;
import com.cxd.blog.model.vo.params.PageParams;
import com.cxd.blog.model.vo.params.PageResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author PGTWO
 * @date 2021/9/30 16:01
 * @description：
 */
@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 分页查询
     *
     * @param pageParams
     * @return
     */
    @Override
    public Result listPermission(PageParams pageParams) {
        Page<Permission> page = new Page<>(pageParams.getCurrentPage(), pageParams.getPageSize());
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(pageParams.getQueryString())) {
            queryWrapper.eq(Permission::getName, pageParams.getQueryString());
        }
        Page<Permission> permissionPage = this.permissionMapper.selectPage(page, queryWrapper);
        PageResult<Permission> pageResult = new PageResult<>();
        pageResult.setList(permissionPage.getRecords());
        pageResult.setTotal(permissionPage.getTotal());
        return Result.success(pageResult);
    }

    /**
     * 增加
     *
     * @param permission
     * @return
     */
    @Override
    public Result add(Permission permission) {
        int row = permissionMapper.insert(permission);
        return row > 0
                ? Result.success(ResultCode.ADD_SUCCESS)
                : Result.fail(ResultCode.ADD_FIELD.getCode(), ResultCode.ADD_FIELD.getMsg());
    }

    /**
     * 更新
     *
     * @param permission
     * @return
     */
    @Override
    public Result update(Permission permission) {
        int row = permissionMapper.updateById(permission);
        return row > 0
                ? Result.success(ResultCode.UPDATE_SUCCESS)
                : Result.fail(ResultCode.UPDATE_FIELD.getCode(), ResultCode.UPDATE_FIELD.getMsg());
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @Override
    public Result deletePermission(Long id) {
        int row = permissionMapper.deleteById(id);
        return row > 0
                ? Result.success(ResultCode.DELETE_SUCCESS)
                : Result.fail(ResultCode.DELETE_FIELD.getCode(), ResultCode.DELETE_FIELD.getMsg());
    }
}
